﻿using LocalizationUtils;
using LocalizationUtils.Language;
using TMPro.EditorUtilities;
using UnityEditor;
using UnityEngine;

namespace LocalizationUtils.Editor
{
    [CustomEditor(typeof(LocalizationTMP3DText))]
    public class LocalizationTMP3DTextEditor : TMP_EditorPanel
    {
        static readonly string[] s_locals =
        {
            "none",
            "en",
            "zh_cn"
        };

        private int currentLocal;

        private SerializedProperty _eKey;
        private SerializedProperty _eNeedAwake;
        private LocalizationTMP3DText _eComponent;

        protected override void OnEnable()
        {
            base.OnEnable();
            _eKey = serializedObject.FindProperty("_key");
            _eNeedAwake = serializedObject.FindProperty("_needAwake");
            _eComponent = (LocalizationTMP3DText)target;
        }


        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            _eKey = serializedObject.FindProperty("_key");
            _eNeedAwake = serializedObject.FindProperty("_needAwake");
            _eComponent = (LocalizationTMP3DText)target;
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(_eNeedAwake);
            EditorGUILayout.PropertyField(_eKey);
            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
                serializedObject.Update();
            }

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Local:");
            int oldLocal = currentLocal;
            currentLocal = EditorGUILayout.Popup(currentLocal, s_locals);
            if (_eComponent._key != 0 && currentLocal != 0 && oldLocal != currentLocal)
            {
                string s = Localize(_eComponent._key, currentLocal);
                if (s != null && _eComponent.text != s)
                {
                    _eComponent.text = s;
                }

                if (s == null)
                {
                    currentLocal = oldLocal;
                }
            }

            EditorGUILayout.EndHorizontal();
            if (GUILayout.Button("重新加载Localize文件"))
            {
                if (currentLocal != 0)
                {
                    string s = Localize(_eComponent._key, currentLocal);
                    if (s != null && _eComponent.text != s)
                    {
                        _eComponent.text = s;
                    }
                }
            }
        }

        public string Localize(long key, int local)
        {
            Lang.Instance.SetNative(LocalizationManager.GetSystemLanguageByLocale(s_locals[local]));
            string v = Lang.Get(key);
            return v;
        }
    }
}